var chartTypeMap = {'line':'折线图','bar':'柱状图','pie':'饼图','scatter':'散点图','radar':'雷达图'}
var seqId=0;

function changeDetailCategory(obj) {
    Ext.getCmp('chartTree').getStore().getProxy().extraParams.detailMode = nowDetailMode
    Ext.getCmp('chartTree').getStore().load()
}

function findSeriesIndex(node) {
    if (node.data.instanceType!=null) {
        return node.parentNode.data.index
    } else {
        if (node.parentNode!=null) {
            return findSeriesIndex(node.parentNode)
        } else {
            return null
        }
    }
    
}


function showFieldDesc(id) {
    Ext.create('Ext.tip.ToolTip', {
        target: 'fieldTipAnchor_'+id,
        closeAction:'destroy',
        title: '描述',
        //anchor: 'bottom',
        autoShow:true,
        maxWidth:1200,
        autoHide:false,
        loader: {
            url: '../app/configdesc?id='+id,
            autoLoad: true
        },
        listeners:{
            hide:function( obj, eOpts ){
                obj.close()
            }
        }
    });
}


function reloadCache() {

    var mb = Ext.MessageBox.show({
        msg: '正在刷新配置, 请等待...',
        progressText: '刷新中...',
        width: 300,
        wait: {
            interval: 200
        },
        animateTarget: Ext.getCmp('reloadCache')
    });


    Ext.Ajax.request({
        url: "../app/reloadcache",
        success:function(response, opts) {
            mb.close()
        }
    })

    /*Ext.MessageBox.show({
            title: '请等待',
            msg: '正在刷新...',
            progressText: '刷新中...',
            width:300,
            progress:true,
            closable:false,
            animateTarget: Ext.getCmp('reloadCache')
        });*/

}


function updateChartBandTree() {
    
    var rootNode = Ext.getCmp('chartTree').getStore().getNodeById('categoryroot')
    var childNodes = rootNode.childNodes
    var obj = {}
    for(var i=0;i<childNodes.length;i++) {
        obj[childNodes[i].data.jsonStr]=""
    }

    
    for(var i=0;i<chartBand[2].children.length;i++) {
        var jsonStr = chartBand[2].children[i].jsonStr
        var node = chartBand[2].children[i]
        console.log(node)
        if (chartSource[jsonStr]!=null && obj[jsonStr]==null && jsonStr!='dataset'&& jsonStr!='Series') {
            
            rootNode.appendChild(node)
        }
        
    }
    


}

function init() {

    
    for(var i=0;i<chartBand[2].children.length;i++) {
        var jsonStr = chartBand[2].children[i].jsonStr
        var children = chartBand[2].children[i].children
        if (jsonStr=="Series") {
            for(var j=0;j<children.length;j++) { 
                serieCategoryMap[children[j].id] = children[j].children
            }
            break
        }
    }

    for (var i in chartOption) {
        if (chartOption[i].jsonStr=="Series") {

            console.log(chartOption[i].children)
            for(var j=0;j<chartOption[i].children.length;j++) {
                var instanceType;
                var id
                for (var k=0;k<chartOption[i].children[j].children.length;k++) {
                    if (chartOption[i].children[j].children[k].optionId=="type") {
                        instanceType = chartOption[i].children[j].children[k].optionValue
                        id = chartOption[i].children[j].id
                        seriesMenuItems.push(
                            {
                                text:instanceType,  
                                //iconCls:'leaf',
                                handler:function(){}
                            }
                        )

                        seriesOption[instanceType] = chartOption[i].children[j]
                        serieTypeCategoryId[instanceType] = id
                        break;
                    }
                    //if (instanceType==record.data){

                    //}
                }


                                                                
            }
        }
    }
}



function updateChartSource() {
    Ext.getCmp('attrPanel').setTitle('图表源码')
    Ext.getCmp('attrPanel').remove(0)
    Ext.getCmp('attrPanel').add(
        {
            xtype:'container',
            layout:'vbox',
            items:[
                {
                    xtype:'container',
                    id:'chartSourceTip',
                    html:'',
                },
                {
                    xtype:'container',
                    width:'100%',
                    height:350,
                    listeners:{
                        render:function() {
                            sourceEditor = ace.edit("sourceEditor");
                            sourceEditor.setTheme("ace/theme/monokai")
                            sourceEditor.setFontSize(20)
                            sourceEditor.session.setMode("ace/mode/javascript");
                            sourceEditor.on("change", function(value){
                                var temp
                                nowChartSourceContent = sourceEditor.session.getValue()
                                try {
                                    temp = JSON.parse(sourceEditor.session.getValue())
                                    chartSource = Ext.clone(temp)
                                } catch(e){
                                    console.log(e)
                                    nowChartSourceTip = '<div style="font-size:20px;color:red">'+e+'</div>'
                                    Ext.getCmp('chartSourceTip').setHtml(nowChartSourceTip)
                                }
                                if (temp!=null) {
                                    nowChartSourceTip = ''
                                    chart1.setOption(temp,{notMerge:true})
                                }
                                

                                Ext.getCmp('chartSourceTip').setHtml(nowChartSourceTip)
                            });
                        }
                    },
                    html:'<div id="sourceEditor">'+'</div>',
                }
            ]
        }
    )
    if (nowChartSourceContent!=null) {
        sourceEditor.session.setValue(nowChartSourceContent)
    } else {
        var jsonStr = JSON.stringify(chartSource, null, "\t");
        sourceEditor.session.setValue(jsonStr)
    }
    console.log(nowChartSourceTip)
    Ext.getCmp('chartSourceTip').setHtml(nowChartSourceTip)

}



function rgb2hex(r, g, b) {
    r = r.toString(16);
    g = g.toString(16);
    b = b.toString(16);
    if (r.length < 2) {
        r = '0' + r;
    }
    if (g.length < 2) {
        g = '0' + g;
    }
    if (b.length < 2) {
        b = '0' + b;
    }
    return (r + g + b).toUpperCase();
}


function updateChildrenCategoryId(idPre,children) {
    if (children.length!=0) {
        for (var i=0;i<children.length;i++) {
            console.log(children[i].id)
            children[i].id = idPre+children[i].id.substring(8)
            updateChildrenCategoryId(idPre,children[i].children)
        }
    }



}

function createSerieBand(type,flag){
    var store = Ext.getCmp('chartTree').getStore()
    var node = store.getNodeById('chartInstance')
    
    if (chartSource.series == null) {
        chartSource.series = []
    }
    //console.log("category"+serieTypeCategoryId[type])

    var children = Ext.clone(serieCategoryMap["category"+serieTypeCategoryId[type]])
    var idPre = "chartInstance"+seqId+"_"
    console.log(idPre+serieTypeCategoryId[type])
    updateChildrenCategoryId(idPre,children)    
    node.appendChild(
    {
        id:idPre+serieTypeCategoryId[type],
        text:chartTypeMap[type],
        leaf:false,
        instanceType:type,
        children:children
    })
    seqId++
    Ext.getCmp('chartTree').expandNode(node)
    if (type=='line' || type=='bar'|| type=='scatter') {
        chartSource = Ext.Object.merge({xAxis:{type:"category"},yAxis:{type:"value"}},chartSource)
    }
    
    if (type=='pie'||type=='radar') {
        chartSource = Ext.Object.merge({},chartSource)
    }

    if (flag) {
        chartSource.series.push({type:type})
        chart1.setOption(chartSource)
    }

    updateChartBandTree()
}



function updateCategoryConfigs(record) {
    Ext.getCmp('attrPanel').setTitle(record.data.text)
    var categoryId 
    if (record.id.indexOf("chartInstance")!=-1) {
        console.log(record.id)
        var flagIndex = record.id.indexOf("_")
        categoryId = record.id.substring(flagIndex+1)
        console.log(categoryId)
    } else {
        categoryId = record.id.substring(8)
    }
    
    if (categoryId!=null) {

        console.log(chartOption[categoryId].children.length)
        var column = 3
        var items = []
        
        var fieldsetItems = {}
        for(var i=0;i<=9;i++) {
            fieldsetItems[i] = []
        }

        var fieldsets = []

        for(var i=0;i<column;i++) {
            items.push({items:[],id:'attrPanelFieldsetForm'+i})
            var ti = 0
            for(var j=0;j<chartOption[categoryId].children.length;j++) {
                var p=chartOption[categoryId].children[j]
                var isHidden = false
                if (nowDetailMode!=null&&nowDetailMode!="") {
                    if (p.detailFlag==null||p.detailFlag=="") {
                        isHidden = false
                    } else {
                        if (p.detailFlag.indexOf(nowDetailMode+"")!=-1) {
                            isHidden = true
                        }
                    }
                }
                if (!isHidden) {
                    if (ti%column==i ) {
                        items[i].items.push(renderField(p,i,ti))
                    }
                    ti++
                }
                
            }
        }


        for (var i=1;i<=9;i++) {
            fieldsets.push({
                    xtype: 'fieldset',
                    id:'attrPanelFieldset'+i,
                    //height:'100%',
                    title: '',
                    collapsible: false,
                    layout: 'column',
                    //scroll:true,
                    defaults: {
                        layout: 'form',
                            xtype: 'container',
                            //scroll:true,
                            defaultType: 'textfield',
                            style: 'width: 33.3333%;'
                        },
                    items: items
            })
        }

        fieldsets.push({
            xtype: 'fieldset',
            id:'attrPanelFieldset0',
            title: '',
            collapsible: false,
            layout: 'column',
            defaults: {
                layout: 'form',
                xtype: 'container',
                defaultType: 'textfield',
                style: 'width: 33.3333%;'
            },
            items: fieldsetItems[0]
        })


        Ext.getCmp('attrPanel').remove(0)
        /*Ext.getCmp('attrPanel').add({
            xtype:'form',
            width:1600,
            height:'100%',
            border:false,
            //autoScroll:true,
            scrollable: true,
            items:[
                {
                    xtype: 'fieldset',
                    id:'attrPanelFieldset',
                    //height:'100%',
                    title: '',
                    collapsible: false,
                    layout: 'column',
                    //scroll:true,
                    defaults: {
                        layout: 'form',
                            xtype: 'container',
                            //scroll:true,
                            defaultType: 'textfield',
                            style: 'width: 33.3333%;'
                        },
                    items: items
                }
            ]
        })*/

    }
}

function buildKeysArray(array,p) {
    for (i in p) {
        array.push(i)
        if ( (p[i] instanceof Object) || (p[i] instanceof Array) ) {
            buildKeysArray(array,p[i])
        } 
    }

}

function removeJsonObject(obj,array) {
    var item = array[0]
    array.splice(0,1)
    if (array.length!=0) {
        if (obj[item]!=null) {
            removeJsonObject(obj[item],array)
        }
    } else {
        delete obj[item]
    }
}

function getJsonObject(obj,array) {
    var item = array[0]
    array.splice(0,1)
    if (array.length!=0) {
        if (obj[item]!=null) {
            return getJsonObject(obj[item],array)
        }
    } else {
        return obj[item]
    }
}



function parseJsonAttr(jsonAttr,value,type) {
    var seriesFlag = false
    if (jsonAttr.indexOf("Series_")!=-1) {
        seriesFlag = true
    }
    console.log(jsonAttr)
    nowChartSourceContent = null 
    var array = jsonAttr.split("_")
    if (seriesFlag) {
        array.splice(0,2)
    }
    var jsonAttr = "{"
    for (i=0;i<array.length;i++) {
        if (i==(array.length-1)) {
            jsonAttr+="\""+array[i]+"\":"
        } else {
            jsonAttr+="\""+array[i]+"\":{"
        }
    }

    if (type=="boolean" || type=="number") {
        jsonAttr+=""+value+""
    } else {
        if (value==null|| value=="") {
            jsonAttr+="\"\""
        } else {
            jsonAttr+="\""+value+"\""
        }    
    } 
    

    
    
    var prefix = ""
    for (i=0;i<array.length;i++) {
        prefix += "}"
    }
        
    jsonAttr +=  prefix  
    
    var json = JSON.parse(jsonAttr)
    console.log(json)

    if (seriesFlag) {
        console.log(value)
        var temp = Ext.clone(chartSource.series[nowSeriesIndex])
        buildKeysArray(array,json)
        if ( type!="boolean" && (value==null|| value=="") ) {

            var array = []
            buildKeysArray(array,json) 
            removeJsonObject(chartSource.series[nowSeriesIndex],array)
        } else {
            chartSource.series[nowSeriesIndex] = Ext.Object.merge(chartSource.series[nowSeriesIndex],json)
        }
    } else {
        if (type!="boolean" && (value==null|| value=="") ) {
            var array = []
            buildKeysArray(array,json) 
            removeJsonObject(chartSource,array)
        } else {
            chartSource = Ext.Object.merge(chartSource,json)
        }
    }

    

    
    //console.log(json)
    console.log(chartSource)
    chart1.setOption(chartSource,{notMerge:true})

}

function formatOptionId(optionId) {
    var result = ""
    var temp = optionId.substring(0, 1).toUpperCase() + optionId.substring(1);  
    for(var i=0;i<temp.length;i++){            
        var a = temp.charAt(i);
        if (i==0) {
            result = ""+a
        } else {
            if( a>64 && a<91 ){              
                result += " "+a                
            }else{                
                result += ""+a          
            } 
        }    
    }
        
    if (optionId=="useUTC") {
        result = "Use UTC"
    }
    return result
}


function renderField(p,col,row) {
    var field 

    var optionValue

    var isHidden = false
    if (nowDetailMode!=null&&nowDetailMode!="") {
        if (p.detailFlag==null||p.detailFlag=="") {
            isHidden = false
        } else {
            if (p.detailFlag.indexOf(nowDetailMode+"")!=-1) {
                isHidden = true
            }
        }
    }
    var array = p.optionJson.replace(/:/g,"_").split("_")

    if (p.optionJson.indexOf("Series:")!=-1) {
        var array = p.optionJson.split(':')
        array.splice(0,2)
        //console.log(nowSeriesIndex)
        //console.log(chartSource.series[nowSeriesIndex])
        optionValue = getJsonObject(chartSource.series[nowSeriesIndex],array)
    } else {
        optionValue = getJsonObject(chartSource,array)
    }

    var isDisplay = ""
    if (nowMode==null || nowMode==false) {
        isDisplay = "display:none"
    }

    var prefix = '<span class="dev" style="'+isDisplay+'">'+
            //'<a href=javascript:setFieldOrder('+p.id+',1) style="color:red">←</a>&nbsp;'+
            //'<a href=javascript:setFieldOrder('+p.id+',2) style="color:red">↑</a>&nbsp;'+
            //'<a href=javascript:setFieldOrder('+p.id+',3) style="color:red">→</a>&nbsp;'+
            //'<a href=javascript:setFieldOrder('+p.id+',4) style="color:red">↓</a>&nbsp;'+
            '<input id="optionOrder'+p.id+'"style="width:30px;" /><a href=javascript:setOptionOrder('+p.id+') style="color:blue">✓</a>&nbsp;'+
            '<a href=javascript:setOptionDetailFlag('+p.id+') style="color:red">✖</a>&nbsp;&nbsp;'+
            '</span>'
    

    if (optionValue==null) {
        //optionValue = p.optionValue
    }
    

    field = { 
        id:'configField'+p.id,
        itemId:p.optionJson.replace(/:/g,"_"),
        listeners:{
            render:function(obj, eOpts) {  
                   
            }, 
            change:function( obj, newValue, oldValue, eOpts) {
                try {
                    parseJsonAttr(obj.itemId,'#'+newValue,p.optionType)
                } catch(e) {
                    console.log(e)
                }
                
            }
        },
        value:optionValue,
        hidden:isHidden,
        xtype:'textfield',
        labelAlign: 'top',
        fieldLabel: prefix+'<a id="fieldTipAnchor_'+p.id+'" href=javascript:showFieldDesc('+p.id+') style="font-weight:bold" color=blue>'+p.optionName+'</a> '+formatOptionId(p.optionId)
    }

    if (p.optionType=="color") {
        optionValue = (optionValue==null||optionValue=="")?'':optionValue
        field = { 
            id:'configField'+p.id,
            itemId:p.optionJson.replace(/:/g,"_"),
            listeners:{
                render:function(obj, eOpts) {  
                    
                }, 
                change:function( obj, newValue, oldValue, eOpts) {
                    
                    if (chart1!=null && newValue!=null && newValue.trim()!="") {
                        try {
                            if (newValue=='RGBA(0,0,0,0)') {
                                parseJsonAttr(obj.itemId,'transparent',p.optionType)
                            } else {
                                var array = newValue.replace('RGB(',"").replace(')',"").split(",")
                                var color = "#"+rgb2hex(array[0], array[1], array[2]);
                                console.log(color)
                                parseJsonAttr(obj.itemId,newValue,p.optionType)
                            }
                            
                        } catch(e) {
                            console.error(e)
                        }
                    } else {
                        parseJsonAttr(obj.itemId,newValue,p.optionType)
                    }

                }
            },
            //value:optionValue,
            value:optionValue,
            format:'RGBA',
            xtype:'colorfield',
            hidden:isHidden,
            labelAlign: 'top',
            fieldLabel: prefix+'<a id="fieldTipAnchor_'+p.id+'" href=javascript:showFieldDesc('+p.id+') style="font-weight:bold" color=blue>'+p.optionName+'</a> '+formatOptionId(p.optionId)
        }
    }

    if (p.optionType=="number") {
        field = { 
            id:'configField'+p.id,
            itemId:p.optionJson.replace(/:/g,"_"),
            listeners:{
                change:function( obj, newValue, oldValue, eOpts) {
                    if (chart1!=null) {
                        parseJsonAttr(obj.itemId,newValue,p.optionType)
                    }
                },
                render:function(obj, eOpts) {  
                    /*Ext.create('Ext.tip.ToolTip', {
                        target: this.id,
                        title: '描述',
                        anchor: 'bottom',
                        maxWidth:1200,
                        autoShow:false,
                        hidden:true,
                        showDelay:100000000000000,
                        autoLoad:false,
                        loader: {
                            url: '../app/configdesc?id='+p.id,
                            autoLoad: false
                        },
                        dismissDelay: 5000 
                    });*/
                }

            },
            value:optionValue,
            hidden:isHidden,
            xtype:'numberfield',
            labelAlign: 'top',
            fieldLabel: prefix+'<a id="fieldTipAnchor_'+p.id+'" href=javascript:showFieldDesc('+p.id+') style="font-weight:bold" color=blue>'+
            p.optionName+'</a> '+formatOptionId(p.optionId)
            /*fieldLabel: '<font style="font-weight:bold" color=blue>'+p.optionName+'</font>'+formatOptionId(p.optionId)
            +' ['+'<a href="javascript:alert(1)">O</a>'+' '+'<a href="javascript:alert(1)">S</a>'+' '+'<a href="javascript:alert(1)">N</a>'+']'*/
        }
    }

    if (p.optionType=="boolean") {
        if (optionValue==null||optionValue=="") {
            optionValue = false
        } else {
            if (optionValue=="true") {
                optionValue = true
            }
            if (optionValue=="false") {
                optionValue = false
            }
        }
         
        field = { 
            id:'configField'+p.id,
            itemId:p.optionJson.replace(/:/g,"_"),
            listeners:{
                change:function( obj, newValue, oldValue, eOpts) {
                    console.log(obj.itemId)
                    if (chart1!=null) {
                        parseJsonAttr(obj.itemId,newValue,p.optionType)
                    }
                                
                },
                render:function(obj, eOpts) {  
                    
                } 
            },
            value:optionValue,
            labelAlign: 'top',
            hidden:isHidden,
            xtype:'checkboxfield',
            fieldLabel: prefix+'<a id="fieldTipAnchor_'+p.id+'" href=javascript:showFieldDesc('+p.id+') style="font-weight:bold" color=blue>'+p.optionName+'</a> '+formatOptionId(p.optionId)
        }
    }

    if (p.optionType=="string") {
        field = { 
            id:'configField'+p.id,
            itemId:p.optionJson.replace(/:/g,"_"),
            listeners:{
                change:function( obj, newValue, oldValue, eOpts) {
                    parseJsonAttr(obj.itemId,newValue,p.optionType)
                },
                render:function(obj, eOpts) {  
                    
                } 
            },
            value:optionValue,
            xtype:'textfield',
            labelAlign: 'top',
            hidden:isHidden,
            //labelAlign: 'bottom',
            fieldLabel: prefix+'<a id="fieldTipAnchor_'+p.id+'" href=javascript:showFieldDesc('+p.id+') style="font-weight:bold" color=blue>'+p.optionName+'</a> '+formatOptionId(p.optionId)
        }
    }


    return field/*{
        xtype: 'fieldcontainer',
        layout:'hbox',
        width:'100%',
        fieldLabel: '',
        items:[field,{xtype:'textfield',fieldLabel:''}]
    }*/
}


